﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace psafth.Common.Extensions
{
    public static class ByteExtensions
    {
        public static ulong ToULong(this byte[] bytes, bool littleEndian = false)
        {
            if (littleEndian)
                Array.Reverse(bytes);

            if (bytes.Length == 2)
                return (ulong)BitConverter.ToInt16(bytes, 0);

            if (bytes.Length == 4)
                return (ulong)BitConverter.ToInt32(bytes, 0);

            if (bytes.Length == 8)
                return BitConverter.ToUInt64(bytes, 0);

            // Fallback if the length of the byte array was unexpected.
            return ulong.Parse(BitConverter.ToString(bytes, 0), System.Globalization.NumberStyles.HexNumber);
        }

        public static int ToInt32(this byte[] bytes, bool littleEndian = false)
        {
            if (bytes.Length > 4)
                throw new ArgumentOutOfRangeException("Byte array with length greater than 4 bytes cannot be converted to 32-bit integer!");

            if (littleEndian)
                Array.Reverse(bytes);

            if (bytes.Length == 2)
                return BitConverter.ToInt16(bytes, 0);

            if (bytes.Length == 4)
                return BitConverter.ToInt32(bytes, 0);

            // Fallback if the length of the byte array was unexpected.
            return int.Parse(BitConverter.ToString(bytes, 0), System.Globalization.NumberStyles.HexNumber);
        }
    }
}
